/*
 * Math.cpp
 *
 *  Created on: 14-Feb-2013
 *      Author: abhijeet
 */

#include "Math.h"


int BinaryToDecimalSimple(const char *binary) {

	int i, endIndex, decimal = 0;

	if (strlen(binary) > 33) {
		cerr << "Binary length is more than 32bit" << endl;
		cerr << "exiting" << endl;
		exit(1);
	}

	endIndex = strlen(binary) - 1;

	for (i = 0; i <= endIndex; i++) {
		decimal += (binary[endIndex - i] - '0') * pow(2, i);
	}
	return decimal;

}
int BinaryToDecimal(const char * binary) {

	//cout << "binary: " << binary << endl;
	//cout << "size " << strlen(binary) << endl;

	char buffer[33];
	strcpy(buffer, binary);

	if (strlen(binary) > 33) {
		cerr << "Binary length is more than 32bit" << endl;
		cerr << "exiting" << endl;
		exit(1);
	}

	//Remove the \n from the binary variable
	//binary[32] = '\0';

	int decimal = 0;
	int endIndex = strlen(binary) - 1;

	int i;

	//If 1 is present at the 0th location then it's a -ve no
	//take two's complement then convert the no
	if (buffer[0] == '1') {
		for (i = 0; i <= endIndex; i++) {
			if (buffer[i] == '1') {
				buffer[i] = '0';
			} else {
				buffer[i] = '1';
			}
		}

		for (i = 0; i <= endIndex; i++) {
			decimal += (buffer[endIndex - i] - '0') * pow(2, i);
		}
		return -1 * (decimal + 1);

	} else {

		for (i = 0; i <= endIndex; i++) {
			decimal += (buffer[endIndex - i] - '0') * pow(2, i);
		}
		return decimal;
	}

}

